package net.caixiaomi.info;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;

import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.callback.WebCallBack;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.logger.Timber;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.ShareModel;
import net.caixiaomi.info.presenter.WebviewPresenter;
import net.caixiaomi.info.ui.dialog.ShareDialogFragment;
import net.caixiaomi.info.ui.football.PaymentActivity;
import net.caixiaomi.info.ui.login.LoginActivity;
import net.caixiaomi.info.ui.mine.RechargeActivity;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.SchemeUtil;
import net.caixiaomi.info.util.ToastUtil;

import org.json.JSONException;

import butterknife.BindView;
import butterknife.OnClick;

public class WebViewActivity extends BaseActivity {

    private WebviewPresenter mPresenter;

    private final String TAG = "JsWebViewActivity";
    @BindView(R.id.container)
    LinearLayout mContainer;
    private WebView mWebView;
    private String mURL = null;
    private MenuItem mShareItem;
    private String mEventId;

    int RESULT_CODE = 0;

    ValueCallback<Uri> mUploadMessage;
    private boolean mNeedUserInfo = false;
    private boolean mNeedShare = false;

    @OnClick(R.id.btn_close)
    void toClose() {
        super.onBackPressed();
    }

    @Override
    protected int layout() {
        return R.layout.act_webview;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        mURL = getIntent().getStringExtra("url");
        mEventId = getIntent().getStringExtra("eventId");
        if (!TextUtils.isEmpty(mEventId)) {

        }
        mWebView = new WebView(getApplicationContext());
        mContainer.addView(mWebView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
//        mWebView.addJavascriptInterface(new AndroidtoJs(), "test");
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setTextZoom(100);
        String ua = "";
        try {
            ua=settings.getDefaultUserAgent(WebViewActivity.this);
            ua="app/android&"+ua;
        } catch (NoSuchMethodError e) {
        }
        settings.setUserAgentString(ua);

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        mWebView.setWebViewClient(mWebClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        loadData();
        changeTitle("操作说明");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            WebView.setWebContentsDebuggingEnabled(true);
//        }

        mPresenter=new WebviewPresenter(this,mWebView, new WebviewPresenter.WebCallBack() {
            @Override
            public void changedTitle(String title) {
                changeTitle(title);
            }

            @Override
            public void hideTitle(boolean hide) {
                if(hide){
                    findViewById(R.id.toolbar).setVisibility(View.GONE);
                }else{
                    findViewById(R.id.toolbar).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void hideDelete(boolean hide) {
                if(hide){
                    findViewById(R.id.btn_close).setVisibility(View.GONE);
                }else{
                    findViewById(R.id.btn_close).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void goShare(String title, String description, String url, String thumbUrl) {
                        ShareModel shareModel = new ShareModel();
                        shareModel.setTitle(title);
                        shareModel.setDescription(description);
                        url=url+"&qd="+AppHelper.getChanel(WebViewActivity.this);
                        shareModel.setUrl(url);
                        shareModel.setThumbUrl(thumbUrl);
                        ShareDialogFragment shareDialog = new ShareDialogFragment();
                        Bundle bundle = new Bundle();
                        bundle.putString("data", JSON.toJSONString(shareModel));
                        shareDialog.setArguments(bundle);
                        shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
            }
        });

    }


    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.article, menu);
        menu.findItem(R.id.btn_collect).setVisible(false);
        mShareItem = menu.findItem(R.id.btn_share);
        mShareItem.setVisible(mNeedShare);
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.btn_share:
                mWebView.evaluateJavascript("javascript:getCxmShare()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        if (!TextUtils.isEmpty(value)) {
                            ShareDialogFragment shareDialog = new ShareDialogFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("data", value);
                            shareDialog.setArguments(bundle);
                            shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
                        }
                    }
                });
                break;
        }
        return true;
    }


    private void loadData() {
        if (TextUtils.isEmpty(mURL)) {
            return;
        }

        // 是否有HTTP前辍
        if (!mURL.startsWith("http") && !mURL.startsWith("file")) {
            mURL = "http://" + mURL;
        }
        StringBuilder url = new StringBuilder(mURL);
        if (url.indexOf("?") < 0) {
            url.append("?");
        }

        if (url.indexOf("showtitle") < 0) {
            url.append("&").append("showtitle=").append("1");
        }
        if (url.indexOf("cfrom") < 0) {
            url.append("&").append("cfrom=").append("app");
        }

        if (url.indexOf("usinfo") > 0) {
            mNeedUserInfo = true;
        }
        if (url.indexOf("cmshare=1") > 0) {
            mNeedShare = true;
        }
        mURL = url.toString();
        mWebView.setVisibility(View.VISIBLE);
//        mURL="http://192.168.31.205:8080/";
        mWebView.loadUrl(mURL);
        Timber.d("url == " + mURL);
    }


    public void pickFile() {
        Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
        chooserIntent.setType("image/*");
        startActivityForResult(chooserIntent, RESULT_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == RESULT_CODE) {
            if (null == mUploadMessage) {
                return;
            }
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_LOGIN:
                    mWebView.reload();
                    break;
                case EventWhat.EVENT_PAYMENT://支付
                    finish();
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed() {
        if (getCurrentFocus() != null) {
            AppHelper.hideKeyboard(getCurrentFocus());
        }
        if(mWebView.canGoBack()){
            mWebView.goBack();
        }else{
            finish();
        }
//        mPresenter.goBack();


//        if (mWebView.canGoBack()) {
//            mWebView.goBack();
//            return;
//        }
//        super.onBackPressed();
    }

    private WebViewClient mWebClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            Timber.d("shouldOverrideUrlLoading == " + url);
//            if (mShareItem != null) {
//                mShareItem.setVisible(url.contains("cmshare=1"));
//            }
            boolean result = false;
            Uri parse = Uri.parse(url);
            String cxmxc = parse.getQueryParameter("cxmxc");
            String extparam = parse.getQueryParameter("extparam");
            String type = parse.getQueryParameter("type");
            if (!TextUtils.isEmpty(cxmxc) && !TextUtils.isEmpty(extparam)) {
                result = true;
                if (!TextUtils.isEmpty(type) && Integer.valueOf(type) == 10 || Integer.valueOf(type) == 11) {
                    if (TextUtils.isEmpty(CommonApp.getToken())) {
                        startActivity(new Intent(WebViewActivity.this, LoginActivity.class));
                        return result;
                    }
                }
                view.evaluateJavascript("javascript:" + extparam + "()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        String title = value.replace("\"", "");
                        if (!TextUtils.isEmpty(title) && !TextUtils.equals("null", title)) {
                            SchemeUtil.parseInWebViewUrl(WebViewActivity.this, url, value);
                        }
                    }
                });
            } else {
                return SchemeUtil.parseInWebViewUrl(WebViewActivity.this, url, null);
            }
            return result;
        }

        public void onReceivedSslError(WebView view,
                                       SslErrorHandler handler, SslError error) {
            handler.proceed();// 接受所有网站的证书
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.setVisibility(View.VISIBLE);
            if (mShareItem != null) {
                mShareItem.setVisible(url.contains("cmshare=1"));
            }
            if (url.indexOf("usinfo") > 0) {
                mNeedUserInfo = true;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            try {
                ToastUtil.s(R.string.C_NET_ERROR);
                view.setVisibility(View.GONE);
                super.onReceivedError(view, errorCode, description, failingUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            view.evaluateJavascript("javascript:getCxmTitle()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
//                    String title = value.replace(\"", "");
//                    if (TextUtils.isEmpty(title) || TextUtils.equals("null", title)) {
//                        changeTitle(getString(R.string.app_name));
//                        return;
//                    }
//                    changeTitle(title);
                }
            });
            if (mNeedUserInfo) {
                JSONObject object = new JSONObject();
                object.put("token", CommonApp.getToken());
                view.loadUrl("javascript:actionMessage('" + object + "')");
                mNeedUserInfo = false;
            }
            //TODO 需要注入token信息
        }

    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
            this.openFileChooser(uploadMsg);
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
            this.openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            pickFile();
        }

        public void onReceivedTitle(WebView view, String title) {
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(mEventId)) {
            StatService.onPageStart(this, mEventId);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!TextUtils.isEmpty(mEventId)) {
            StatService.onPageEnd(this, mEventId);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {

            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }

            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
//            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }

    }

//    // 继承自Object类
//    public class AndroidtoJs extends Object {
//
//        // 定义JS需要调用的方法
//        // 被JS调用的方法必须加入@JavascriptInterface注解
//        @JavascriptInterface
//        public void appNative(String msg) {
//            try {
//                if(TextUtils.isEmpty(msg)){
//                    return;
//                }
//                org.json.JSONObject obj=new org.json.JSONObject(msg);
//                String methodName=obj.getString("methodName");
//                switch (methodName){
//                    case "showTitle":
//                        String title=obj.getString("title");
//                        changeTitle(title);
//                        break;
//                    case "hideTitle":
//
//                        break;
//                    case "hideDelete":
//
//                        break;
//                    case "getToken":
//                        JSONObject object = new JSONObject();
//                        object.put("token", CommonApp.getToken());
//                        mWebView.loadUrl("javascript:actionMessage('" + object + "')");
//                        mNeedUserInfo = false;
//                        break;
//                    case "pushPayment":
//                        String payToken=obj.getString("payToken");
//                        Intent payIntent = new Intent(WebViewActivity.this, PaymentActivity.class);
//                        payIntent.putExtra("payToken", payToken);
//                        startActivity(payIntent);
//                        break;
//                    case "pushRechange":
//                        String price=obj.getString("price");
//                        JSONObject priceObj=new JSONObject();
//                        priceObj.put("price",price);
//                        Intent rechargeIntent = new Intent(WebViewActivity.this, RechargeActivity.class);
//                        rechargeIntent.putExtra("data",priceObj.toString());
//                        startActivity(rechargeIntent);
//                        break;
//                    case "goShare":
//
//                        break;
//                    case "pushUrl":
//                        String url=obj.getString("url");
//                        break;
//                    case "closeWeb":
//                        finish();
//                        break;
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
